#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import locale
import pymysql

from libs.Config import Config
from libs.properties import Properties

try:
    from PyQt5.QtCore import QFile, QIODevice, QTextStream
except ImportError:
    if sys.version_info.major >= 3:
        import sip
        sip.setapi('QVariant', 2)
    from PyQt4.QtCore import QFile, QIODevice, QTextStream


class StringBundle:

    __create_key = object()

    def __init__(self, create_key, mydb, localeStr):
        assert(create_key == StringBundle.__create_key), "StringBundle must be created using StringBundle.getBundle"

        self.mydb = mydb

        self.idToMessage = {}
        self.localeStr = localeStr
        self.classListItem = []

        self.loadStringByMysql()

        # path1=os.path.abspath('.')   # 表示当前所处的文件夹的绝对路径
        # print("当前所处的文件夹的绝对路径:" + path1)
        # path2=os.path.abspath('..')  # 表示当前所处的文件夹上一级文件夹的绝对路径
        # print("当前所处的文件夹上一级文件夹的绝对路径:" + path2)

        # paths = self.__createLookupFallbackList(localeStr)
        # for path in paths:
        #     self.__loadBundle(path)
        # path = "./strings-zh-CN.properties"
        # self.__loadBundle(path)

    def loadStringByMysql(self):
        try:
            # SQL 查询语句
            sql = "select id, name, cn_name, en_name from sys_labelImg"

            # 执行SQL语句, 获取所有记录列表
            results = self.mydb.executeSql(sql)

            for row in results:
                properties = Properties(row[0], row[1], row[2], row[3])
                if properties.get_name().startswith('class_'):
                    self.classListItem.append(properties)
                else:
                    self.idToMessage[properties.get_name()] =  properties

        except:
            print("Error: unable to fecth data")

    def getClassListItem(self):
        return self.classListItem

    @classmethod
    def getBundle(cls, mydb, localeStr=None):
        if localeStr is None:
            try:
                localeStr = locale.getlocale()[0] if locale.getlocale() and len(locale.getlocale()) > 0 else os.getenv('LANG')
            except:
                print('Invalid locale')
                localeStr = 'en'

        return StringBundle(cls.__create_key, mydb, localeStr)

    def getString(self, stringId):
        assert(stringId in self.idToMessage), "Missing string id : " + stringId
        properties = self.idToMessage[stringId]
        if self.localeStr == "zh-CN":
            return properties.get_cnName()
        else:
            return properties.get_enName()